package com.lib76.buildCode.service;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipUtils {

	public static boolean compressDirectory(File file,String targetPath){
		try{
			if(file.exists() && file.isDirectory() && StringUtils.isNotBlank(targetPath)){
				OutputStream out = null;
				if(targetPath.matches("^.*\\.zip$")){
					File targetFile = new File(targetPath);
					if(!targetFile.exists()){
						targetFile.getParentFile().mkdirs();
						targetFile.createNewFile();
						out = FileUtils.openOutputStream(targetFile);
					}else{
						out = FileUtils.openOutputStream(targetFile);
					}
				}else{
					File targetFile = new File(targetPath + "/" + file.getName()+".zip");
					targetFile.getParentFile().mkdirs();
					targetFile.createNewFile();
					out = FileUtils.openOutputStream(targetFile);
				}
				ZipOutputStream zipOut = new ZipOutputStream(out);
				zipOut.setEncoding("UTF-8");
				for(File child:file.listFiles()){
					write(child,zipOut,"");
				}
				zipOut.finish();
				zipOut.close();
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	private static void write(File file,ZipOutputStream out,String parentPath) throws IOException{
		if(file.isDirectory()){
			File[] children = file.listFiles();
			if(children.length > 0){
				for(File child:file.listFiles()){
					write(child,out,parentPath + file.getName() + "/");
				}
			}else{
				ZipEntry entry = new ZipEntry(parentPath +file.getName() + "/");
				out.putNextEntry(entry);
				out.closeEntry();
			}
		}else{
			ZipEntry entry = new ZipEntry(parentPath +file.getName());
			out.putNextEntry(entry);
			out.write(FileUtils.readFileToByteArray(file));
			out.closeEntry();
		}
	}
}
